using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ZedGraph;

namespace GeneticProgrammingUI_CS
{
   

    public partial class frmProcess : Form
    {
        //ArrayList barData = new ArrayList();
        int colorIndx = 0;
        Color[] colors = { Color.Tan, Color.Yellow, Color.Green, Color.Blue, Color.Purple, Color.Aqua, Color.Brown, Color.Coral, Color.Crimson, Color.MintCream };
        private static int CURR_BAR_DATA_COUNT = 0;
        ArrayList xValue, yValue;

        public frmProcess(ArrayList xValue, ArrayList yValue)
        {
            this.xValue = xValue;
            this.yValue = yValue;
            InitializeComponent();
        }

        private void frmProcess_Load(object sender, EventArgs e)
        {
            myTimer.Interval = 5000;
            myTimer.Enabled = true;
            populateExpectedExpData();
            // File System Watcher stuff. 
            fsWatcher.Path = frmMain.DEFAULT_DIR;
            
        }

        private void myTimer_Tick(object sender, EventArgs e)
        {
            if (pbTimer.Value<180)
            pbTimer.Value += 1;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            //this.Close();
            this.Visible = false;
        }

        private void fsWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
        {
            //tbResults.Text += "\nGot File: " + e.Name;
            System.Threading.Thread.Sleep(50);// Magic Number 
            getGraphData(e);
        }

        private void getGraphData(System.IO.RenamedEventArgs e)
        {
            FileStream file = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.None);
            StreamReader sr = new StreamReader(file);
            
            String CURR_GEN = e.Name;
            CURR_GEN = CURR_GEN.Substring(3, (CURR_GEN.IndexOf('.') - 3));
            int counter = 1;
            string tempData;
            string exp="";
            double fitLevel = 0;
            ArrayList xDataAry = new ArrayList();
            ArrayList yDataAry = new ArrayList();

            while (sr != null)
            {
                tempData = sr.ReadLine();
                if (tempData == null) break;
                
                if (counter == 1) exp = tempData;
                else if (counter == 2) fitLevel = double.Parse(tempData.Trim());
                else if (counter > 2)
                {
                    string[] tempDataAry = tempData.Split(',');
                    xDataAry.Add(double.Parse(tempDataAry[0].Trim()));
                    yDataAry.Add(double.Parse(tempDataAry[1].Trim()));
                }
                counter += 1;  
            }
            sr.Close();
            file.Close();

            CURR_BAR_DATA_COUNT++;// next bar record.
            tbResults.Text += " Expression from Generation "+CURR_GEN+": "+ exp+"\r\n";

            if (colorIndx == 9) colorIndx = 0;
            Color expColor = colors[colorIndx];
            colorIndx += 1;

            populateExpData(xDataAry, yDataAry, expColor); //Expression Graph
            
            ProcessBarGraph(fitLevel, expColor); //Bar Graph
            this.Refresh();
            
        }

        public void populateExpectedExpData()
        {
            populateExpData(xValue, yValue, Color.Red);      
        }

        //Expression Graph
        public void populateExpData(ArrayList xExpList, ArrayList yExpList, Color expColor)
        {
            CreateExpressionGraph(zedGraphExp, xExpList, yExpList, expColor);
        }
       
        // Call this method from the Form_Load method, passing your ZedGraphControl
        public void CreateExpressionGraph(ZedGraphControl zgc, ArrayList xExpList, ArrayList yExpList, Color lineColor)
        {
            GraphPane myPane = new GraphPane();
            myPane=zgc.GraphPane;

            // Set the titles and axis labels
            myPane.Title.Text = "Expression Graph";
            myPane.XAxis.Title.Text = "X Axis";
            myPane.YAxis.Title.Text = "Y Axis";

            double x, y;
            PointPairList list = new PointPairList();
            for (int i = 0; i < xExpList.Count; i++)
            {
                x = (double)xExpList[i];
                y = (double)yExpList[i];
                list.Add(x, y);
            }           

            // Generate a red curve with diamond
            // symbols, and "Porsche" in the legend
            LineItem myCurve = myPane.AddCurve("Parabola", list, lineColor, SymbolType.Diamond);

            // Set the Y axis intersect the X axis at an X value of 0.0
            myPane.YAxis.Cross = 0.0;
            // Turn off the axis frame and all the opposite side tics
            myPane.Chart.Border.IsVisible = false;
            myPane.XAxis.MajorTic.IsOpposite = false;
            myPane.XAxis.MinorTic.IsOpposite = false;
            myPane.YAxis.MajorTic.IsOpposite = false;
            myPane.YAxis.MinorTic.IsOpposite = false;
            myPane.Legend.IsVisible = false; // turning legend off.

            // Calculate the Axis Scale Ranges
            zgc.AxisChange();
        }

        //BarGrpaph
        public void ProcessBarGraph(double fLevel, Color expColor)
        {
          DrawBarGraph(zedGraphFitness,fLevel, expColor);
        }

        // Call this method from the Form_Load method, passing your ZedGraphControl
        private void DrawBarGraph(ZedGraphControl z1,double fLevel, Color expColor)
        {
            GraphPane myPane = z1.GraphPane;
            myPane.Title.Text = "Generation Error Level";
            myPane.XAxis.Title.Text = "Generation";
            myPane.YAxis.Title.Text = "Error Rate";
            myPane.Legend.IsVisible = false;
            //if (fLevel >= 100.00)// if more we will level at 100
            //    barData.Add(100.00);
            //else
            //    barData.Add(fLevel);// adding the current stuff in the ArrayList.

            PointPairList list = new PointPairList(); // populating the list to draw.
            list.Clear();

            if (fLevel>=100)
                list.Add(CURR_BAR_DATA_COUNT, 100, 1);
            else
                list.Add(CURR_BAR_DATA_COUNT, fLevel,1);

            BarItem myCurve = myPane.AddBar("Multi-Colored Bars", list, Color.Blue);

            myCurve.Bar.Fill = new Fill(expColor);
            myCurve.Bar.Fill.Type = FillType.GradientByZ;

           // myCurve.Bar.Fill.RangeMin = 0;
            //myCurve.Bar.Fill.RangeMax = 4;

            //myPane.Chart.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45);
            //myPane.Fill = new Fill(Color.White, Color.FromArgb(255, 255, 225), 45);
            
            // Tell ZedGraph to calculate the axis ranges
            z1.AxisChange();
        }
    }
}